package com.kedacom.demo.spring.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * AbstractWebSocketClientHandler
 * @author luocanfeng
 * @date 2017年8月11日
 */
public abstract class AbstractWebSocketClientHandler extends TextWebSocketHandler {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	protected WebSocketClient webSocketClient;

	public void setWebSocketClient(WebSocketClient webSocketClient) {
		this.webSocketClient = webSocketClient;
	}

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		logger.info("建链成功，session id：{}", session.getId());
	}

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		String text = message.getPayload();
		logger.info("收到来自服务器端的消息：{}", text);
	}

	@Override
	protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
		logger.error("不支持二进制消息，请发字符串文本消息！");
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable e) throws Exception {
		logger.error("传输错误：{}", e.getMessage());
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		logger.info("与服务器断开连接，session id：{}，close status：[code: {}, reason: {}]", session.getId(), status.getCode(),
				status.getReason());
	}

}
